// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

// 人物节点
var ClickManager = require('ClickManager')
var CreatorHelper = require('CreatorHelper')
var TableManager = require('TableManager')
var UserManager = require('UserManager')
var NetworkManager = require('NetworkManager')
var AudioManager = require('AudioManager')
var UnitTools = require('UnitTools')

cc.Class({
    extends: cc.Component,

    properties: {
        figurePrefab: cc.Prefab,  // 人物预制体
        figureContainer: cc.Node, // 人物容器
        tableId: cc.Label, // 房间id
    },

    onLoad () {
        CreatorHelper.loadPrefab('prefabs/Bgm', (node) => {
            this.node.addChild(node)
            node.getComponent('Bgm')._playGame()
        })

        var gamePath = 'Canvas/bg/game_table/'
        var btnNode  = gamePath+'StartBtn'
        var btnPath  = gamePath+'StartBtn/StartBgImg'
        var totalPath = gamePath+'total/text/'

        this.posCount = 5
        this.downBtnStatus = false
        this.innings = 0
        this.linkCount = 0

        // 准备状态
        this.realyNode = cc.find(btnNode)
        this.realyBtn  = cc.find(btnPath)
        this.realyTxtNode = cc.find(btnPath+'/text')
        this.realyTxt = this.realyTxtNode.getComponent(cc.Label)

        // 统计节点
        this.lowNoteNode = cc.find(totalPath+'lowNote')
        this.totalAmountNode = cc.find(totalPath+'totalAmount')
        this.lowNoteTxt = this.lowNoteNode.getComponent(cc.Label)
        this.totalAmountTxt = this.totalAmountNode.getComponent(cc.Label)

        // 牌桌基本配置
        this.config = null
        this.user = null
        TableManager.user = null

        this.init()
    },

    onDestroy () {
        TableManager.user = null
    },

    // 初始化信息
    init () {
        this.initDownMenu()
        this.initDownMenuBtn()
        this.initPrefab()
        this.initGameInfo()

        TableManager.initBtn()
        TableManager.initFillBtn()
    },

    // 游戏牌桌信息
    initGameInfo () {
        NetworkManager.onConnectedToGame((gameService) => {
            gameService.proxy.gameBaseInfo(UserManager.token, UserManager.tid, (res) => {
                if (res.ok && res.code === 200) {
                    var obj = JSON.parse(res.datas)
                    cc.log('玩家信息:', obj)
                    this.config = obj.config
                    this.user = obj.user
                    this.innings = obj.innings
                    TableManager.gameing = obj.gameing
                    TableManager.settlement = obj.settlement
                    UserManager.myuid = obj.myuid
                    this.setTableBaseConfig()
                    if (TableManager.settlement && this.linkCount < 1) {
                        cc.log('进来了')
                        setTimeout(() => {
                            TableManager.settlementAfterStartGame()
                        }, 1000)
                    }
                    this.linkCount++
                }
            })
        })
    },

    // 设置牌桌基本配置
    setTableBaseConfig () {
        if (this.config != null) {
            let roomInfo = `游戏牌局: ${this.config.innings}  当前牌局: ${this.innings}  房间ID: ${this.config.id} `

            this.tableId.string = roomInfo
            this.lowNoteTxt.string = this.config.low_grade+' '
            this.totalAmountTxt.string = TableManager.getTotalBet(this.user) + ' '
        }

        if (this.user != null) {
            this.createFigure()
        }
    },

    // 下拉菜单
    initDownMenu () {
        var downBtn = cc.find('Canvas/bg/down/hs')
        var downSprite = 'images/smallimages/'
        var path = ''

        CreatorHelper.setNodeClickEvent(downBtn, () => {
            let btnSprite = downBtn.getComponent(cc.Sprite)
            let downMenu  = cc.find('Canvas/bg/downmenu')

            this.downBtnStatus = !this.downBtnStatus
            path = this.downBtnStatus ? downSprite + 'hss' : downSprite + 'hs'
            CreatorHelper.changeSpriteFrame(btnSprite, path)
            downMenu.active = this.downBtnStatus
        })
    },

    // 下拉菜单按钮事件
    initDownMenuBtn () {
        var path  = 'Canvas/bg/downmenu/bg/'
        var home = cc.find(path+'home'),
            set  = cc.find(path+'set'),
            help = cc.find(path+'help')

        CreatorHelper.setNodeClickEvent(home, () => {
            TableManager.confirmModel('确定退出房间吗?', () => {
                TableManager.user = null
                NetworkManager.onCloseFormGame()
                TableManager.exitTable(UserManager.myuid, UserManager.tid)
            })
        })

        CreatorHelper.setNodeClickEvent(set, () => {
            this.setModel.active = true
        })

        CreatorHelper.setNodeClickEvent(help, () => {
            this.HelpModel.active = true
        })

        CreatorHelper.setNodeClickEvent(this.realyBtn, () => {
            this.doReadly()
        })
    },

    // 初始化预制体
    initPrefab () {
        var canvas = cc.find('Canvas')
        var pPath = 'prefabs/model/'

        CreatorHelper.loadPrefab(pPath+'modelSet', (node) => {
            canvas.addChild(node)
            this.setModel = node
            this.setModel.active = false
        })

        CreatorHelper.loadPrefab(pPath+'modelGameHelp', (node) => {
            canvas.addChild(node)
            this.HelpModel = node
            this.HelpModel.active = false
        })

        CreatorHelper.loadPrefab('prefabs/settlement/win', (node) => {
            canvas.addChild(node)
            TableManager.WinModel = node
            TableManager.WinModel.active = false

            let btnGroup = node.getChildByName('btnGroup')
            let confirm = btnGroup.getChildByName('confirm_bg')
            let cancel = btnGroup.getChildByName('cancel_bg')

            // 继续游戏
            CreatorHelper.setNodeClickEvent(confirm, () => {
                cc.log('继续游戏')
                TableManager.settlementAfterStartGame()
            })

            // 退出游戏
            CreatorHelper.setNodeClickEvent(cancel, () => {
                cc.log('退出游戏')
                TableManager.settlementAfterExitGame()
            })
        })

        CreatorHelper.loadPrefab('prefabs/settlement/lose', (node) => {
            canvas.addChild(node)
            TableManager.LoseModel = node
            TableManager.LoseModel.active = false

            let btnGroup = node.getChildByName('btnGroup')
            let confirm = btnGroup.getChildByName('confirm_bg')
            let cancel = btnGroup.getChildByName('cancel_bg')

            // 继续游戏
            CreatorHelper.setNodeClickEvent(confirm, () => {
                cc.log('继续游戏')
                TableManager.settlementAfterStartGame()
            })

            // 退出游戏
            CreatorHelper.setNodeClickEvent(cancel, () => {
                cc.log('退出游戏')
                TableManager.settlementAfterExitGame()
            })
        })
    },

    // 人物节点信息
    createFigure () {
        let newLength = Object.keys(this.user).length,
            oldLength = TableManager.user === null ? 0 : Object.keys(TableManager.user).length

        if (newLength > oldLength) {
            TableManager.addFigureNode(this.user, this.figureContainer, this.figurePrefab)
        } else if (newLength === oldLength) {
            TableManager.updateFigureNode(this.user, this.figureContainer, this.figurePrefab)
        } else if (newLength < oldLength) {
            TableManager.rmFigureNode(this.user, this.figureContainer, this.figurePrefab)
        }

        TableManager.user = this.user
        for (let k in this.user) {
            if (this.user[k].uid == UserManager.myuid) {
                UserManager.identity = this.user[k]['status']
            }
        }

        if (UserManager.identity === 0) {
            this.realyTxt.string = '准 备'
        } else if (UserManager.identity === 1) {
            this.realyTxt.string = '已准备'
        } else if (UserManager.identity === 2) {
            this.realyTxt.string = '开始游戏'
        }

        // 准备状态
        if (!TableManager.gameing) {
            this.realyNode.active = true
            this.realyTxtNode.active = true
            TableManager.btnGroupNode.active = false // 隐藏按钮组
        } else {
            TableManager.getGameStartInfo(UserManager.myuid, UserManager.tid)
            this.realyNode.active = false
            this.realyTxtNode.active = false
            TableManager.btnGroupNode.active = true // 显示按钮组
        }

        if (TableManager.settlement) {
            TableManager.btnGroupNode.active = false // 隐藏按钮组
        }
    },

    // 准备
    doReadly () {
        TableManager.handsReStart()
        if (UserManager.identity === 2) {
            // 开始游戏
            NetworkManager.onConnectedToGame((gameService) => {
                gameService.proxy.gameStart(UserManager.myuid, UserManager.tid, (res) => {
                    if (res.ok && res.code === 200) {
                        cc.log('开始游戏')
                    } else {
                        TableManager.alertModel(res.msg)
                    }
                })
            })
        } else {
            // 准备游戏
            NetworkManager.onConnectedToGame((gameService) => {
                gameService.proxy.gameReadyOrNot(UserManager.myuid, UserManager.tid, (res) => {
                    if (res.ok && res.code === 200) {
                        cc.log('游戏准备')
                    } else {
                        TableManager.alertModel(res.msg)
                    }
                })
            })
        }
    },

    // 实时更新
    update (dt) {
        if (UserManager.recePushToGame != null) {
            cc.log('接收主动推送的数据:', UserManager.recePushToGame)
            switch (UserManager.recePushToGame.msg) {
                case 'pushJoinTable':
                    cc.log('初始化信息')
                    break

                case 'pushGameStart':
                    cc.log('开始游戏，获取手牌信息')
                    TableManager.getGameStartInfo(UserManager.myuid, UserManager.tid)
                    if (!UnitTools.isNullOrUndefined(UserManager.recePushToGame.datas)) {
                        let obj = JSON.parse(UserManager.recePushToGame.datas)
                        TableManager.showOperMsg(obj)
                    }
                    break

                case 'pushGameReStart':
                    cc.log('继续游戏')
                    TableManager.getGameStartInfo(UserManager.myuid, UserManager.tid)
                    break

                case 'pushGameStartAllIn':
                    cc.log('操作游戏，下家已梭哈自动过牌')
                    let obj = JSON.parse(UserManager.recePushToGame.datas)
                    let uid = obj.uid
                    if (uid == UserManager.myuid) {
                        TableManager.autoACard()
                    }
                    break

                case 'pushGameStartSettlement':
                    cc.log('操作游戏都已经完成结算')
                    TableManager.settlementCurMatch()
                    break

                case 'pushGameSuccessSettlement':
                    cc.log('结算完成获取结算结果')
                    TableManager.getCurMatchResults()
                    break

                case 'pushAllLeaveRoom':
                    cc.log('解散房间')
                    TableManager.allLeaveRoom()
                    break
            }

            this.initGameInfo()
            UserManager.recePushToGame = null
        }
    },
});
